<template>
  <view class="staff-management-page">
    <!-- 搜索栏 -->
    <view class="search-section">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索员工姓名或工号"
        @search="handleSearch"
        @clear="handleClear"
        shape="round"
        :show-action="false"
      ></u-search>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <u-tabs
        :list="filterTabsWithCount"
        :current="Number(currentFilter)"
        @change="handleFilterChange"
        keyName="name"
        lineWidth="30"
        lineHeight="3"
        activeStyle="color: #2d8cf0; font-weight: bold;"
        inactiveStyle="color: #606266;"
      ></u-tabs>
    </view>

    <!-- 员工列表 -->
    <scroll-view 
      scroll-y="true" 
      class="staff-scroll" 
      :style="{ height: scrollViewHeight }"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="staff-list">
        <view
          v-for="staff in staffList"
          :key="staff.id"
          class="staff-item"
          @click="handleStaffDetail(staff)"
        >
          <view class="staff-avatar">
            <u-avatar
              :src="staff.avatar"
              :text="staff.realName ? staff.realName.charAt(0) : ''"
              size="60"
            ></u-avatar>
          </view>
          
          <view class="staff-info">
            <view class="staff-header">
              <text class="staff-name">{{ staff.realName }}</text>
              <u-tag
                :text="getStatusText(staff.status)"
                :type="getStatusType(staff.status)"
                size="mini"
              ></u-tag>
            </view>
            
            <view class="staff-details">
              <view class="detail-item">
                <u-icon name="account" size="14" color="#666"></u-icon>
                <text class="detail-text">{{ staff.employeeNo || '暂无工号' }}</text>
              </view>
              <view class="detail-item">
                <u-icon name="briefcase" size="14" color="#666"></u-icon>
                <text class="detail-text">{{ staff.position || '暂无职位' }}</text>
              </view>
              <view class="detail-item">
                <u-icon name="home" size="14" color="#666"></u-icon>
                <text class="detail-text">{{ staff.propertyCompanyName || '暂无物业公司' }}</text>
              </view>
            </view>
          </view>
          
          <view class="staff-actions">
            <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="staffList.length === 0 && !loading" class="empty-state">
        <u-empty
          text="暂无员工信息"
          mode="data"
        ></u-empty>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="staffList.length > 0" class="load-more-tip">
        <text v-if="loading" class="tip-text">加载中...</text>
        <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
        <text v-else class="tip-text">没有更多数据了</text>
      </view>
    </scroll-view>

    <!-- 浮动添加按钮 -->
    <view class="fab-button" @click="handleAddStaff">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, nextTick } from 'vue'
import { staffApi } from '@/api/staff'
import { dataScopeApi } from '@/api/property'
import { propertyInfoApi } from '@/api/propertyInfo'
import { useAuthStore } from '@/store/auth'

export default {
  name: 'StaffManagement',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const refreshing = ref(false)
    const hasMore = ref(true)
    const searchKeyword = ref('')
    const currentFilter = ref(0)
    const staffList = ref([])
    const scrollViewHeight = ref('calc(100vh - 200px)')
    
    // 配置选项 - 遵循App端编码规范
    const config = ref({
      enablePropertyCompanyName: false, // 禁用物业公司名称获取，因为API已返回propertyCompanyName
      showDebugInfo: false // 调试信息开关
    })

    // 分页数据
    const pagination = ref({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 筛选标签 - 严格按照App端编码规范实现
    const filterTabs = ref([
      { name: '全部', value: null, count: 0, index: 0 },
      { name: '在职', value: 1, count: 0, index: 1 },
      { name: '离职', value: 0, count: 0, index: 2 },
      { name: '待入职', value: 2, count: 0, index: 3 }
    ])

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: '在职',
        0: '离职',
        2: '待入职'
      }
      return statusMap[status] || '未知'
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        1: 'success',
        0: 'error',
        2: 'warning'
      }
      return typeMap[status] || 'default'
    }

    // 更新状态统计
    const updateStatusCount = (allStaffList) => {
      if (!allStaffList || allStaffList.length === 0) {
        filterTabs.value.forEach(tab => {
          tab.count = 0
        })
        return
      }

      // 统计各状态员工数量
      const statusCounts = {
        1: 0, // 在职
        0: 0, // 离职
        2: 0  // 待入职
      }

      allStaffList.forEach(staff => {
        if (statusCounts.hasOwnProperty(staff.status)) {
          statusCounts[staff.status]++
        }
      })

      // 更新标签计数
      filterTabs.value[0].count = allStaffList.length // 全部
      filterTabs.value[1].count = statusCounts[1]     // 在职
      filterTabs.value[2].count = statusCounts[0]     // 离职
      filterTabs.value[3].count = statusCounts[2]     // 待入职

      console.log('状态统计更新:', {
        全部: filterTabs.value[0].count,
        在职: filterTabs.value[1].count,
        离职: filterTabs.value[2].count,
        待入职: filterTabs.value[3].count
      })
    }

    // 计算带数量的标签
    const filterTabsWithCount = computed(() => {
      const result = filterTabs.value.map(tab => ({
        name: `${tab.name}${tab.count > 0 ? ` (${tab.count})` : ''}`,
        value: tab.value,
        count: tab.count
      }))
      console.log('filterTabsWithCount:', result)
      return result
    })

    // 计算滚动视图高度
    const calculateScrollHeight = () => {
      try {
        const systemInfo = uni.getSystemInfoSync()
        const windowHeight = systemInfo.windowHeight
        const statusBarHeight = systemInfo.statusBarHeight || 0
        const navbarHeight = 44 // 导航栏内容高度
        const searchHeight = 60 // 搜索栏高度
        const tabsHeight = 44 // 状态标签高度
        const padding = 32 // 上下边距
        
        // 计算实际可用高度
        const calculatedHeight = windowHeight - statusBarHeight - navbarHeight - searchHeight - tabsHeight - padding
        
        scrollViewHeight.value = `${calculatedHeight}px`
      } catch (error) {
        console.error('计算高度失败:', error)
        scrollViewHeight.value = 'calc(100vh - 200px)'
      }
    }

    // 获取用户物业公司ID数组
    const getUserPropertyCompanyIds = async () => {
      try {
        const authStore = useAuthStore()
        const userInfo = authStore.userInfo
        
        // 如果是超级管理员，返回空数组（表示可以查看所有物业公司的员工）
        if (userInfo?.isSuperAdmin) {
          return []
        }
        
        // 获取用户有权限的物业公司ID数组
        const response = await dataScopeApi.getUserPropertyCompany()
        if (response && response.code === 200 && response.data) {
          return response.data.propertyCompanyIds || []
        }
        
        // 如果API调用失败，使用用户信息中的物业公司ID
        if (userInfo?.propertyCompanyId) {
          return [userInfo.propertyCompanyId]
        }
        
        return []
      } catch (error) {
        console.warn('获取用户物业公司ID数组失败:', error)
        const authStore = useAuthStore()
        const userInfo = authStore.userInfo
        if (userInfo?.propertyCompanyId) {
          return [userInfo.propertyCompanyId]
        }
        return []
      }
    }

    // 获取物业公司名称
    const getPropertyCompanyName = async (propertyCompanyId) => {
      try {
        if (!propertyCompanyId) {
          return '暂无物业公司'
        }
        
        const response = await propertyInfoApi.getPropertyCompanyInfo(propertyCompanyId)
        if (response && response.code === 200 && response.data) {
          return response.data.companyName || '暂无物业公司'
        }
        return '暂无物业公司'
      } catch (error) {
        console.warn('获取物业公司名称失败:', error)
        return '暂无物业公司'
      }
    }

    // 为员工数据添加物业公司名称 - 遵循App端编码规范
    const enrichStaffWithPropertyCompanyName = async (staffList) => {
      if (!staffList || staffList.length === 0) {
        return staffList
      }

      // 获取所有唯一的物业公司ID
      const propertyCompanyIds = [...new Set(staffList.map(staff => staff.propertyCompanyId).filter(id => id))]
      
      // 如果没有物业公司ID，直接返回原数据
      if (propertyCompanyIds.length === 0) {
        return staffList.map(staff => ({
          ...staff,
          propertyCompanyName: '暂无物业公司'
        }))
      }

      // 批量获取物业公司信息 - 严格遵循错误处理规范
      const propertyCompanyMap = new Map()
      
      try {
        const companyPromises = propertyCompanyIds.map(async (id) => {
          try {
            const response = await propertyInfoApi.getPropertyCompanyInfo(id)
            
            // 严格按照App端编码规范处理响应
            if (response && response.code === 200 && response.data) {
              return {
                id,
                name: response.data.companyName || '暂无物业公司'
              }
            } else {
              // 处理业务错误
              console.warn(`获取物业公司信息失败 - ID: ${id}, 响应:`, response)
              return {
                id,
                name: '暂无物业公司'
              }
            }
          } catch (error) {
            // 处理网络错误 - 遵循App端编码规范
            console.error(`获取物业公司信息网络错误 - ID: ${id}:`, error)
            return {
              id,
              name: '暂无物业公司'
            }
          }
        })
        
        const companyResults = await Promise.all(companyPromises)
        companyResults.forEach(company => {
          propertyCompanyMap.set(company.id, company.name)
        })
        
        console.log('物业公司信息获取完成:', propertyCompanyMap)
        
      } catch (error) {
        // 处理整体错误
        console.error('批量获取物业公司信息失败:', error)
        // 不显示错误提示，静默处理，确保页面正常显示
      }

      // 为每个员工添加物业公司名称
      return staffList.map(staff => ({
        ...staff,
        propertyCompanyName: propertyCompanyMap.get(staff.propertyCompanyId) || '暂无物业公司'
      }))
    }

    // 加载员工列表
    const loadStaffList = async (isRefresh = false) => {
      try {
        if (isRefresh) {
          refreshing.value = true
          pagination.value.pageNum = 1
          staffList.value = []
        } else {
          loading.value = true
        }
        
        // 获取用户物业公司ID数组
        const propertyCompanyIds = await getUserPropertyCompanyIds()
        
        // 准备请求参数
        const selectedTab = filterTabs.value[currentFilter.value]
        const params = {
          pageNum: pagination.value.pageNum,
          pageSize: pagination.value.pageSize,
          keyword: searchKeyword.value,
          status: selectedTab?.value,
          propertyCompanyIds: propertyCompanyIds.length > 0 ? propertyCompanyIds.join(',') : undefined
        }
        
        // 调用后端API获取员工列表
        const response = await staffApi.getStaffList(params)
        
        if (response && response.code === 200 && response.data) {
          const { records, total } = response.data
          
          let enrichedRecords = records || []
          
          // 根据配置决定是否获取物业公司名称 - 遵循App端编码规范
          if (config.value.enablePropertyCompanyName) {
            // 检查员工数据是否包含物业公司ID
            const hasPropertyCompanyIds = records && records.some(staff => staff.propertyCompanyId)
            
            if (hasPropertyCompanyIds) {
              try {
                enrichedRecords = await enrichStaffWithPropertyCompanyName(records || [])
                if (config.value.showDebugInfo) {
                  console.log('物业公司名称获取成功:', enrichedRecords)
                }
              } catch (error) {
                console.error('获取物业公司名称失败，使用默认值:', error)
                // 降级处理：使用默认的物业公司名称
                enrichedRecords = (records || []).map(staff => ({
                  ...staff,
                  propertyCompanyName: '暂无物业公司'
                }))
              }
            } else {
              // 如果员工数据中没有物业公司ID，直接添加默认值
              enrichedRecords = (records || []).map(staff => ({
                ...staff,
                propertyCompanyName: '暂无物业公司'
              }))
            }
          } else {
            // 配置未启用时，直接添加默认的物业公司名称
            enrichedRecords = (records || []).map(staff => ({
              ...staff,
              propertyCompanyName: '暂无物业公司'
            }))
          }
          
          if (isRefresh) {
            staffList.value = enrichedRecords
          } else {
            staffList.value = [...staffList.value, ...enrichedRecords]
          }
          
          // 更新分页信息
          pagination.value.total = total || 0
          hasMore.value = staffList.value.length < pagination.value.total
          
          // 更新状态统计（仅在全部状态下更新）
          if (currentFilter.value === 0) {
            updateStatusCount(enrichedRecords)
          }
        } else {
          // API调用失败，使用模拟数据
          console.warn('API调用失败，使用模拟数据')
          const mockData = [
            {
              id: 1,
              realName: '张居民',
              employeeNo: '暂无工号',
              position: '暂无职位',
              department: '暂无部门',
              propertyCompanyId: 1,
              propertyCompanyName: '智慧社区物业管理有限公司',
              status: 1,
              avatar: ''
            },
            {
              id: 2,
              realName: '瓜哥',
              employeeNo: '暂无工号',
              position: '暂无职位',
              department: '暂无部门',
              propertyCompanyId: 1,
              propertyCompanyName: '智慧社区物业管理有限公司',
              status: 1,
              avatar: ''
            },
            {
              id: 3,
              realName: '毛哥',
              employeeNo: '暂无工号',
              position: '物业管理员',
              department: '暂无部门',
              propertyCompanyId: 1,
              propertyCompanyName: '智慧社区物业管理有限公司',
              status: 1,
              avatar: ''
            }
          ]
          
          // 根据状态筛选模拟数据
          let filteredMockData = mockData
          if (selectedTab?.value !== null && selectedTab?.value !== undefined) {
            filteredMockData = mockData.filter(staff => staff.status === selectedTab.value)
          }
          
          if (isRefresh) {
            staffList.value = filteredMockData
          } else {
            staffList.value = [...staffList.value, ...filteredMockData]
          }
          
          // 更新分页信息
          pagination.value.total = filteredMockData.length
          hasMore.value = staffList.value.length < pagination.value.total
          
          // 更新状态统计（仅在全部状态下更新）
          if (currentFilter.value === 0) {
            updateStatusCount(mockData)
          }
        }
        
      } catch (error) {
        console.error('加载员工列表失败:', error)
        
        // 网络错误时使用模拟数据
        const mockData = [
          {
            id: 1,
            realName: '张居民',
            employeeNo: '暂无工号',
            position: '暂无职位',
            department: '暂无部门',
            propertyCompanyId: 1,
            propertyCompanyName: '智慧社区物业管理有限公司',
            status: 1,
            avatar: ''
          },
          {
            id: 2,
            realName: '瓜哥',
            employeeNo: '暂无工号',
            position: '暂无职位',
            department: '暂无部门',
            propertyCompanyId: 1,
            propertyCompanyName: '智慧社区物业管理有限公司',
            status: 1,
            avatar: ''
          },
          {
            id: 3,
            realName: '毛哥',
            employeeNo: '暂无工号',
            position: '物业管理员',
            department: '暂无部门',
            propertyCompanyId: 1,
            propertyCompanyName: '智慧社区物业管理有限公司',
            status: 1,
            avatar: ''
          }
        ]
        
        // 根据状态筛选模拟数据
        const selectedTab = filterTabs.value[currentFilter.value]
        let filteredMockData = mockData
        if (selectedTab?.value !== null && selectedTab?.value !== undefined) {
          filteredMockData = mockData.filter(staff => staff.status === selectedTab.value)
        }
        
        if (isRefresh) {
          staffList.value = filteredMockData
        } else {
          staffList.value = [...staffList.value, ...filteredMockData]
        }
        
        pagination.value.total = filteredMockData.length
        hasMore.value = staffList.value.length < pagination.value.total
        
        // 更新状态统计（仅在全部状态下更新）
        if (currentFilter.value === 0) {
          updateStatusCount(mockData)
        }
        
        uni.showToast({
          title: '网络异常，显示模拟数据',
          icon: 'none'
        })
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }

    // 搜索员工
    const handleSearch = (keyword) => {
      console.log('搜索员工:', keyword)
      searchKeyword.value = keyword
      loadStaffList(true)
    }

    // 清除搜索
    const handleClear = () => {
      searchKeyword.value = ''
      loadStaffList(true)
    }

    // 筛选变化 - 严格按照App端编码规范实现
    const handleFilterChange = (index) => {
      console.log('handleFilterChange 被调用，参数:', index, '类型:', typeof index)
      console.log('当前 currentFilter.value:', currentFilter.value, '类型:', typeof currentFilter.value)
      
      // 处理u-tabs组件传递的参数 - 支持多种参数格式
      let actualIndex = index
      
      // 如果传递的是对象，提取index属性
      if (typeof index === 'object' && index !== null) {
        actualIndex = index.index
        console.log('从对象中提取索引:', actualIndex)
      }
      
      // 参数校验 - 确保索引有效
      if (typeof actualIndex !== 'number' || actualIndex < 0 || actualIndex >= filterTabs.value.length) {
        console.error('无效的标签索引:', actualIndex, 'filterTabs.length:', filterTabs.value.length)
        // 使用默认值防止错误
        actualIndex = 0
        console.warn('使用默认索引:', actualIndex)
      }
      
      // 防止重复切换
      if (currentFilter.value === actualIndex) {
        console.log('相同标签，跳过切换')
        return
      }
      
      // 更新当前筛选状态
      currentFilter.value = actualIndex
      const selectedTab = filterTabs.value[actualIndex]
      
      // 安全检查
      if (!selectedTab) {
        console.error('未找到对应的标签:', actualIndex)
        return
      }
      
      console.log('筛选变化:', selectedTab.name, '状态值:', selectedTab.value)
      
      // 重新加载数据
      loadStaffList(true)
    }

    // 下拉刷新
    const onRefresh = () => {
      loadStaffList(true)
    }

    // 上拉加载更多
    const loadMore = () => {
      if (!loading.value && hasMore.value) {
        pagination.value.pageNum++
        loadStaffList()
      }
    }

    // 查看员工详情
    const handleStaffDetail = (staff) => {
      // 传递员工ID和物业公司ID，确保查询唯一性
      const propertyCompanyId = staff.propertyCompanyId || ''
      uni.navigateTo({
        url: `/pages/property-work/staff-detail?id=${staff.id}&propertyCompanyId=${propertyCompanyId}`
      })
    }

    // 添加员工
    const handleAddStaff = () => {
      uni.navigateTo({
        url: '/pages/property-work/staff-add'
      })
    }

    // 页面加载
    onMounted(() => {
      calculateScrollHeight()
      loadStaffList()
    })

    return {
      loading,
      refreshing,
      hasMore,
      searchKeyword,
      currentFilter,
      staffList,
      scrollViewHeight,
      filterTabs,
      filterTabsWithCount,
      config,
      getStatusText,
      getStatusType,
      handleSearch,
      handleClear,
      handleFilterChange,
      onRefresh,
      loadMore,
      handleStaffDetail,
      handleAddStaff
    }
  }
}
</script>

<style lang="scss" scoped>
.staff-management-page {
  min-height: 100vh;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-section {
  background: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  flex-shrink: 0;
}

.filter-section {
  background: #fff;
  padding: 0 30rpx 20rpx;
  border-bottom: 1rpx solid #eee;
  flex-shrink: 0;
}

.staff-scroll {
  flex: 1;
  min-height: 0;
}

.staff-list {
  padding: 20rpx 30rpx;
  
  .staff-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    width: 100%;
    box-sizing: border-box;
    
    &:active {
      transform: scale(0.98);
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    }
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .staff-avatar {
      margin-right: 20rpx;
      flex-shrink: 0;
    }
    
    .staff-info {
      flex: 1;
      
      .staff-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;
        
        .staff-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
      }
      
      .staff-details {
        .detail-item {
          display: flex;
          align-items: center;
          margin-bottom: 8rpx;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .detail-text {
            margin-left: 10rpx;
            font-size: 26rpx;
            color: #666;
            word-break: break-all;
          }
        }
      }
    }
    
    .staff-actions {
      margin-left: 20rpx;
      flex-shrink: 0;
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.fab-button {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  background: #2d8cf0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(45, 140, 240, 0.3);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .staff-list {
    padding: 15rpx 20rpx;
    
    .staff-item {
      padding: 20rpx;
      margin-bottom: 15rpx;
      
      .staff-info {
        .staff-header {
          .staff-name {
            font-size: 28rpx;
          }
        }
        
        .staff-details {
          .detail-item {
            .detail-text {
              font-size: 24rpx;
            }
          }
        }
      }
    }
  }
  
  .search-section, .filter-section {
    padding: 15rpx 20rpx;
  }
}

@media screen and (min-width: 769px) {
  .staff-management-page {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style>
